# remove all variables from memory and garbage collection
rm(list=ls())
gc()
##           used (Mb) gc trigger (Mb) max used (Mb)
## Ncells  714820 38.2    1168576 62.5  1168576 62.5
## Vcells 1270307  9.7    2060183 15.8  1862799 14.3
# load visualization libraries
library(ggplot2)
library(dygraphs)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(animation)

# difference between simple and advanced one
# time series example
# basic one
data_ts <- sin(c(1:100)/5)
plot(1:100, data_ts, type = "l")

plot(ts(data_ts))

# ggplot usage
# data.frame (table) way

df_ts <- data.frame(value = data_ts,
                    time = 1:length(data_ts))

ggplot(df_ts, aes(time, value)) + 
  geom_line() +
  theme_bw()

# dygraphs usage
# must use pipes %>%
dygraph(df_ts[, c("time", "value")]) %>%
  dyOptions(fillGraph = TRUE, fillAlpha = 0.5,
            strokeWidth = 2) %>%
  dyRangeSelector()
# plotly usage
ggplotly() # calls last plot
## We recommend that you use the dev version of ggplot2 with `ggplotly()`
## Install it with: `devtools::install_github('hadley/ggplot2')`
# animation in R
saveGIF({
  oopt = ani.options(interval = 0.2, nmax = 50)
  for(i in 1:ani.options("nmax")){
    print(ggplot(df_ts[i:(i+50),], aes(time, value)) + 
            geom_line() +
            theme_bw())
    ani.pause()
  }
}, movie.name = "example.gif", ani.height = 450, ani.width = 650)
## Executing: 
## "convert -loop 0 -delay 20 Rplot1.png Rplot2.png Rplot3.png
##     Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png
##     Rplot9.png Rplot10.png Rplot11.png Rplot12.png Rplot13.png
##     Rplot14.png Rplot15.png Rplot16.png Rplot17.png Rplot18.png
##     Rplot19.png Rplot20.png Rplot21.png Rplot22.png Rplot23.png
##     Rplot24.png Rplot25.png Rplot26.png Rplot27.png Rplot28.png
##     Rplot29.png Rplot30.png Rplot31.png Rplot32.png Rplot33.png
##     Rplot34.png Rplot35.png Rplot36.png Rplot37.png Rplot38.png
##     Rplot39.png Rplot40.png Rplot41.png Rplot42.png Rplot43.png
##     Rplot44.png Rplot45.png Rplot46.png Rplot47.png Rplot48.png
##     Rplot49.png Rplot50.png "example.gif""
## Output at: example.gif
## [1] TRUE
# shiny!